package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    /**
     * 微信接口 =》 获取openid
     */
    public static final String WX_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO loginDTO) {

        //1.根据用户授权码去微信获取用户唯一标识(因为用户唯一标识是不会变的)
        String openId = getOpenId(loginDTO.getCode());
        //2.判断openid是否为空，如果为空表示登录失败
        if (openId == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3.根据openid去数据库查询,判断是否为新用户
        User user = userMapper.findUserByOpenId(openId);
        //4.如果是新用户,需要注册
        if (user == null) {
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            //需要注册,需要返回`用户id`
            userMapper.save(user);
        }
        // 5. 返回用户对象
        return user;
    }

    /**
     * 根据授权码去获取微信的openid
     *
     * @param code
     * @return
     */
    public String getOpenId(String code) {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String jsonStr = HttpClientUtil.doGet(WX_URL, map);
        Map<String, String> maps = (Map) JSON.parse(jsonStr);
        return maps.get("openid");
    }
}
